<template>
  <div class="box">
    <div class="head-fixed">
      <div class="head">
        <div class="head-div">
          <img
            src="../../assets/zjt2.png"
            alt=""
            class="back"
            @click="back()"
          />
        </div>
        <div class="head-search">添加意向职位</div>
        <div @click="save">保存</div>
      </div>
    </div>
    <div class="content">
      <!--      求职意向start-->
      <div class="inpBox">
        <span>职位种类</span>
        <div @click="prop(0)">
          <input
            type="text"
            v-model="postValue"
            placeholder="请选择职位种类"
            readonly
          />
        </div>
      </div>
      <div class="inpBox">
        <span>工作城市</span>
        <div @click="prop(1)">
          <input
            type="text"
            v-model="cityValue"
            placeholder="请选择工作城市"
            readonly
          />
        </div>
      </div>
      <div class="inpBox">
        <span>期望薪资</span>
        <div @click="prop(2)">
          <input
            type="text"
            v-model="payValue"
            placeholder="请选择期望薪资"
            readonly
          />
        </div>
      </div>
      <div class="inpBox">
        <span>求职状态</span>
        <div @click="prop(3)">
          <input
            type="text"
            v-model="stateValue"
            placeholder="请选择求职状态"
            readonly
          />
        </div>
      </div>
      <div class="inpBox">
        <span>工作年限</span>
        <div @click="prop(4)">
          <input
            type="text"
            v-model="workYear"
            placeholder="请选择工作年限"
            readonly
          />
        </div>
      </div>
    </div>
    <!--    通过操作postIf变量控制弹出框的显示和隐藏-->
    <mt-popup v-model="postIf" position="bottom">
      <p class="mt-p">
        <span @click="off(0)">取消</span>
        <span>请选择职位</span>
        <span @click="on(0)">确定</span>
      </p>
      <mt-picker
        :slots="post"
        @change="postChange"
        value-key="positionTitle"
        class="picker"
      ></mt-picker>
    </mt-popup>
    <mt-popup v-model="cityIf" position="bottom">
      <p class="mt-p">
        <span @click="off(1)">取消</span>
        请选择城市
        <span @click="on(1)">确定</span>
      </p>
      <mt-picker
        :slots="city"
        valueKey="name"
        :visibleItemCount="5"
        @change="cityOn"
      ></mt-picker>
    </mt-popup>
    <mt-popup v-model="payIf" position="bottom">
      <p class="mt-p">
        <span @click="off(2)">取消</span>
        请选择薪资
        <span @click="on(2)">确定</span>
      </p>
      <mt-picker
        :slots="payList"
        @change="payChange"
        value-key="salaryRange"
        class="picker"
      ></mt-picker>
    </mt-popup>
    <mt-popup v-model="stateIf" position="bottom">
      <p class="mt-p">
        <span @click="off(3)">取消</span>
        请选择求职状态
        <span @click="on(3)">确定</span>
      </p>
      <mt-picker
        :slots="stateLimit"
        @change="stateChange"
        value-key="jobStatus"
        class="picker"
      ></mt-picker>
    </mt-popup>
    <mt-popup v-model="YearIf" position="bottom">
      <p class="mt-p">
        <span @click="off(4)">取消</span>
        请选择工作年限
        <span @click="on(4)">确定</span>
      </p>
      <mt-picker
        :slots="WorkYear"
        @change="yearChange"
        value-key="workYear"
        class="picker"
      ></mt-picker>
    </mt-popup>
  </div>
</template>

<script>
import { Popup, Picker } from "mint-ui";
//引入省市区数据json文件
import threeLevelAddress from "../../assets/address.json";

var postValue = "";
var cityValue = "";
var payValue = "";
var stateValue = "";
var workYear = "";
export default {
  inject: ["reload"],
  name: "work",
  components: { Popup, Picker },
  created() {
    // created 在模板渲染成html前调用，即通常初始化某些属性值，然后再渲染成视图
    this.getData();
  },
  mounted() {
    // mounted在模板渲染成html后调用，通常是初始化页面完成后，再对html的dom节点进行一些需要的操作
  },
  // data() 为变量赋值等
  data() {
    return {
      // status为状态，0是新增，1是修改
      status: localStorage.status,
      userId: localStorage.getItem("userId"),
      state: "",
      postValue: "",
      postAct: 0,
      postIf: false,
      post: [
        // 第一个 slot，用于显示一级职位
        {
          // 该 slot 的宽度比例
          flex: 1,
          // 默认选中的索引
          defaultIndex: 0,
          // 选项列表
          values: [],
          // 样式类名
          className: "slot1",
          // 文字对齐方式
          textAlign: "center"
        },
        // 分割线
        {
          // 是否为分割线
          divider: true,
          // 分割线的内容
          content: "-",
          // 样式类名
          className: "slot2"
        },
        // 第二个 slot，用于显示二级职位
        {
          // 该 slot 的宽度比例
          flex: 1,
          // 选项列表
          values: [],
          // 样式类名
          className: "slot3",
          // 文字对齐方式
          textAlign: "center"
        },
        // 分割线
        {
          // 是否为分割线
          divider: true,
          // 分割线的内容
          content: "-",
          // 样式类名
          className: "slot2"
        },
        // 第三个 slot，用于显示三级职位
        {
          // 该 slot 的宽度比例
          flex: 1,
          // 选项列表
          values: [],
          // 样式类名
          className: "slot3",
          // 文字对齐方式
          textAlign: "center"
        }
      ],
      postValueId: "",
      //工作城市
      cityValue: "",
      cityAct: 0,
      cityIf: false,
      city: [
        //省
        {
          flex: 1,
          values: this.getProvinceArr(), //省份数组
          className: "slot1",
          textAlign: "center"
        },
        //分隔符
        {
          divider: true,
          content: "",
          className: "slot2"
        },
        //市
        {
          flex: 1,
          values: this.getCityArr("北京市"),
          className: "slot3",
          textAlign: "center"
        },
        {
          divider: true,
          content: "",
          className: "slot4"
        },
        //县
        {
          flex: 1,
          values: this.getCountyArr("北京市", "北京市"),
          className: "slot5",
          textAlign: "center"
        }
      ],
      regionInit: false,
      cityValueId: "",
      //期望薪资
      payValue: "",
      payAct: 0,
      payIf: false,
      payList: [
        {
          values: []
        }
      ],
      payValueId: "",
      //求职状态
      stateValue: "",
      stateAct: 0,
      stateIf: false,
      stateLimit: [
        {
          values: []
        }
      ],
      stateValueId: "",
      //工作年限
      workYear: "",
      yearAct: 0,
      YearIf: false,
      WorkYear: [
        {
          values: []
        }
      ],
      workYearId: ""
    };
  },
  // methods 编写js函数
  methods: {
    //弹出框列表的所有数据
    getData() {
      // 从后端得到数据
      this.$http({
        url: this.apiURL + "/userResume/list",
        method: "post"
      }).then(({ data }) => {
        console.log(data);
        let positionTypeList = data.positionTypeList;
        let salaryList = data.salaryList;
        let jobStatusList = data.jobStatusList;
        let workYearList = data.workYearList;
        //职位种类数据
        this.post[0].values = positionTypeList;
        this.post[2].values = positionTypeList[0].list2;
        this.post[4].values = positionTypeList[0].list2[0].list3;
        //期望薪资数据
        this.payList[0].values = salaryList;
        //求职状态数据
        this.stateLimit[0].values = jobStatusList;
        //工作年限数据
        this.WorkYear[0].values = workYearList;
      });
    },
    // 保存按钮
    save() {
      console.log(this.status);

      if (this.status == 0) {
        this.addData();
      } else if (this.status == 1) {
        this.updateData();
      } else {
        console.log('无效的状态值。未执行任何操作。');
      }
    },
    //添加数据
    addData() {
      this.$http({
        url: this.apiURL + "/userIntentionJob/save",
        method: "post",
        data: {
          'positionId': this.postValueId,
          'cityId': this.cityValueId,
          'expectedSalary': this.payValueId,
          'jobStatus': this.stateValueId,
          'workYear': this.workYearId,
          'userId': this.userId,
        },
      })
        .then(({ data }) => {
          // 成功处理
          console.log(data);
          this.$router.push({
            name: "usersResume",
          });
        })
        .catch(error => {
          // 错误处理
          console.error("Upload error: ", error);
        });
    },
    // 更新数据
    updateData() {
      this.$http({
        url: this.apiURL + "/userIntentionJob/update",
        method: "post",
        data: {
          'id':this.$route.params.id,
          'positionId': this.postValueId,
          'cityId': this.cityValueId,
          'expectedSalary': this.payValueId,
          'jobStatus': this.stateValueId,
          'workYear': this.workYearId,
          'userId': this.userId,
        },
      })
        .then(({ data }) => {
          // 成功处理
          console.log(data);
          this.$router.push({
            name: "job",
          });
        })
        .catch(error => {
          // 错误处理
          console.error("Upload error: ", error);
        });
    },
    back() {
      this.$router.go(-1); //返回上一层
    },
    //弹出框的显示隐藏，对v-model的值取反
    prop(i) {
      if (i === 0) {
        this.postIf = !this.postIf;
      } else if (i === 1) {
        this.cityIf = !this.cityIf;
      } else if (i === 2) {
        this.payIf = !this.payIf;
      } else if (i === 3) {
        this.stateIf = !this.stateIf;
      } else if (i === 4) {
        this.YearIf = !this.YearIf;
      }
    },
    // 处理职位选择器（mt-picker）中的一级职位选择变化事件
    postChange(picker, values) {
      // 检查数据结构，确保 values[0] 和 values[1] 包含 list2 和 list3
      if (values[0] && values[0].list2 && values[1] && values[1].list3) {
        // 设置第二个选择器的选项
        picker.setSlotValues(1, values[0].list2);
        // 设置第三个选择器的选项
        picker.setSlotValues(2, values[1].list3);
        // 获取并赋值职位的值
        postValue = values[2].positionTitle;
        this.postValueId = values[2].id;
      }
    },
    // 处理城市选择器（mt-picker）中的一级省份选择变化事件
    cityOn(picker, values) {
      if (this.regionInit) {
        // 设置城市和县区选项的值
        picker.setSlotValues(1, this.getCityArr(values[0]["name"]));
        picker.setSlotValues(
          2,
          this.getCountyArr(values[0]["name"], values[1]["name"])
        );
        // 获取城市和县区的值
        cityValue = values[2]["name"];
        this.cityValueId = values[2]["code"];
      } else {
        this.regionInit = true;
      }
    },
    // 处理薪资选择器（mt-picker）中的薪资选择变化事件
    payChange(picker, values) {
      if (values[0] && values[0].hasOwnProperty("salaryRange")) {
        //赋予全局变量为选择内容
        payValue = values[0].salaryRange;
        //赋予当前选中的选项的id属性值 用于表单提交
        this.payValueId = values[0].id;
        // this.payValueId = picker.values[0].id;
      }
    },
    // 处理求职状态选择器（mt-picker）中的状态选择变化事件
    stateChange(picker, values) {
      if (values[0] && values[0].hasOwnProperty("jobStatus")) {
        stateValue = values[0].jobStatus;
        this.stateValueId = values[0].id;
      }
    },
    // 处理工作年限选择器（mt-picker）中的状态选择变化事件
    yearChange(picker, values) {
      if (values[0] && values[0].hasOwnProperty("workYear")) {
        workYear = values[0].workYear;
        this.workYearId = values[0].id;
      }
    },
    // 确定按钮
    on(i) {
      // debugger
      if (i === 0) {
        this.postValue = postValue;
        this.postIf = false;
      } else if (i === 1) {
        this.cityValue = cityValue;
        this.cityIf = false;
      } else if (i === 2) {
        this.payValue = payValue;
        this.payIf = false;
      } else if (i === 3) {
        this.stateValue = stateValue;
        this.stateIf = false;
      } else if (i === 4) {
        this.workYear = workYear;
        this.YearIf = false;
      }
    },

    // 取消按钮
    off(i) {
      if (i === 0) {
        // this.post = ""; /*自己改过的，以前是post = "" ; */
        this.postIf = false;
      } else if (i === 1) {
        cityValue = "";
        this.cityIf = false;
      } else if (i === 2) {
        payValue = "";
        this.payIf = false;
      } else if (i === 3) {
        stateValue = "";
        this.stateIf = false;
      } else if (i === 4) {
        workYear = "";
        this.YearIf = false;
      }
    },
    //遍历json，返回省级对象数组
    getProvinceArr() {
      let provinceArr = [];
      threeLevelAddress.forEach(function(item) {
        let obj = {};
        obj.name = item.name;
        obj.code = item.code;
        provinceArr.push(obj);
      });
      return provinceArr;
    },
    //遍历json，返回市级对象数组
    getCityArr(province) {
      // console.log("省：" + province);
      let cityArr = [];
      threeLevelAddress.forEach(function(item) {
        if (item.name === province) {
          item.children.forEach(function(args) {
            let obj = {};
            obj.name = args.name;
            obj.code = args.code;
            cityArr.push(obj);
          });
        }
      });
      return cityArr;
    },
    //遍历json，返回县级对象数组
    getCountyArr(province, city) {
      let countyArr = [];
      threeLevelAddress.forEach(function(item) {
        if (item.name === province) {
          item.children.forEach(function(args) {
            if (args.name === city) {
              args.children.forEach(function(param) {
                let obj = {};
                obj.name = param.name;
                obj.code = param.code;
                countyArr.push(obj);
              });
            }
          });
        }
      });
      return countyArr;
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
html,
body,
.tac,
.box,
.tab-left,
.tab-left .el-menu {
  height: 100%;
}

.box {
  width: 100%;
  background: #fff;
}

.head-fixed {
  width: 100%;
  height: 43px;
  position: fixed;
  z-index: 999;
}

.head {
  background: #3e63a8;
  color: #fff;
  width: 100%;
  box-sizing: border-box;
  padding: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
}

.back {
  width: 14px;
  height: 14px;
}

.head div img {
  width: 20px;
  height: 20px;
}

.head-search {
  box-sizing: border-box;
  flex: 1;
  text-align: center;
  font-size: 14px;
}

.content {
  position: relative;
  top: 43px;
  width: 100%;
  box-sizing: border-box;
  padding: 0 20px;
}

.inpBox {
  width: 100%;
  box-sizing: border-box;
  display: flex;
  border-bottom: 1px solid #eee;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  font-size: 14px;
}

.inpBox input {
  border: 0;
  flex: 1;
  outline: none;
  font-size: 14px;
  height: 30px;
  text-align: right;
}

.inpBox div {
  display: flex;
  align-items: center;
}

.inpBoxs {
  width: 100%;
  box-sizing: border-box;
  display: flex;
  flex-flow: column;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
}

.inpBoxs .inpBox {
  border: 0;
}

.inpBoxs textarea {
  width: 100%;
  height: 150px;
  margin-top: 10px;
  box-sizing: border-box;
  padding: 10px;
}
</style>
